import create from "zustand";
import { UserRole, AuthUser } from "../types/roles";

// 通知
export interface NoticeItem {
  id: string;
  type: "info" | "success" | "warning" | "error";
  message: string;
  desc?: string;
  read?: boolean;
  time: string;
}

/**
 * 患者-专属全局状态
 */
interface PatientState {
  lastMedication?: string;
  unreadConsult?: number;
}
/**
 * 医护-专属全局状态
 */
interface DoctorState {
  todayAppointments?: number;
  unreadReports?: number;
}

interface GlobalState {
  user: AuthUser | null;
  setUser: (user: AuthUser | null) => void;

  loading: boolean;
  setLoading: (loading: boolean) => void;

  notices: NoticeItem[];
  addNotice: (n: NoticeItem) => void;
  markNoticeRead: (id: string) => void;
  clearNotices: () => void;

  // 患者/医护角色下的专属状态
  patient?: PatientState;
  doctor?: DoctorState;
  setPatientState: (s: Partial<PatientState>) => void;
  setDoctorState: (s: Partial<DoctorState>) => void;
}

export const useGlobalStore = create<GlobalState>((set, get) => ({
  user: null,
  setUser: user => set({ user }),

  loading: false,
  setLoading: loading => set({ loading }),

  notices: [],
  addNotice: n => set(state => ({ notices: [...state.notices, n] })),
  markNoticeRead: id => set(state => ({
    notices: state.notices.map(n => n.id === id ? { ...n, read: true } : n),
  })),
  clearNotices: () => set({ notices: [] }),

  setPatientState: (s) => set(state => ({ patient: { ...state.patient, ...s } })),
  setDoctorState: (s) => set(state => ({ doctor: { ...state.doctor, ...s } }))
}));
